package com.liu.shop.interceptor;


import com.liu.shop.common.constant.AuthConstants;
import com.liu.shop.common.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 拦截用户的请求，判断是否登录
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private final ThreadLocal<UserVo> threadLocal = new ThreadLocal();

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    public UserVo get() {
        return threadLocal.get();
    }

    //拦截订单页面的所有请求，判断是否登录，没有登录就直接返回到登录页面
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取存在redis中的用户信息
        UserVo userVo = (UserVo) request.getSession().getAttribute(AuthConstants.LOGIN_USER);

        String requestURI1 = request.getRequestURI();

        boolean match = antPathMatcher.match("/order/updateOrderStatus", requestURI1);

        // 用户登录或者请求的是修改订单的状态接口应该放行
        if (userVo != null || match) {
            threadLocal.set(userVo);
            return true;
        } else {

            StringBuffer url = request.getRequestURL();
            url.replace(17,21,"81");

            // 获取请求地址中的参数并存入到map中
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (parameterMap != null && parameterMap.size() > 0) {
                url.append("?");
                // 获取查询参数
                for (Map.Entry<String, String[]> stringEntry : request.getParameterMap().entrySet()) {
                    String key = stringEntry.getKey();
                    String[] value = stringEntry.getValue();
                    url.append(key).append("=").append(value[0]).append("&");
                }
            }
            log.debug("跳转的地址为：{}",url);
            response.sendRedirect("http://localhost:81/auth/loginUser.html?returnUrl=" + url);
            return false;
        }

    }

}
